package com.wdy.balking;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName: WashingMachine
 * @Description: TODO
 * @Date: 2019/12/31 9:46
 * @Author: wangdy001
 * @Version: 1.0
 */
public class WashingMachine {
    private static final Logger LOGGER = LoggerFactory.getLogger(WashingMachine.class);

    private WashMachineState state;
    private DelayProvider provider;

    WashingMachine(){
        this((time, timeUnit, task) -> {
            try {
                Thread.sleep(timeUnit.toMillis(time));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            task.run();
        });
    }

    WashingMachine(DelayProvider provider){
        this.provider = provider;
        this.state = WashMachineState.ENABLED;
    }

    public void washing(){
        synchronized (this) {
            if(state == WashMachineState.WASHING) {
                LOGGER.error("{},  is busying! error! ", Thread.currentThread().getName());
                return;
            }
            state = WashMachineState.WASHING;
        }
        LOGGER.error("{},  is washing! ", Thread.currentThread().getName());
        provider.executeAfterDelay(20, TimeUnit.MILLISECONDS, this::endOfWashing);
    }

    public void endOfWashing(){
        synchronized (this) {
            state = WashMachineState.ENABLED;
            LOGGER.error("{},  finish washing!", Thread.currentThread().getName());
        }
    }
}
